package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.po.Emp;
import com.itheima.domain.po.EmpExpr;
import com.itheima.domain.po.LoginResult;
import com.itheima.domain.query.EmpQueryParam;
import com.itheima.domain.vo.PageResult;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpExprMapper empExprMapper;

    @Override
    public PageResult<Emp> pageEmp(EmpQueryParam param) {
        //参数校验
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        if (page == null || pageSize == null) {
            throw new RuntimeException("参数错误");
        }
        Page<Emp> empPage = Page.of(page, pageSize);
        //分页查询
        String name = param.getName();
        Integer gender = param.getGender();
        LocalDate begin = param.getBegin();
        LocalDate end = param.getEnd();
//        QueryWrapper<Emp> queryWrapper = new QueryWrapper<Emp>()
//                .like(StringUtils.isNotBlank(name), "name", name)
//                .eq(gender != null, "gender", gender)
//                .between(begin != null && end != null && begin.isBefore(end), "entry_date", begin, end)
//                .orderByDesc("update_time");
//        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<Emp>()
//                .like(StringUtils.isNotBlank(name), Emp::getName, name)
//                .eq(gender != null, Emp::getGender, gender)
//                .between(begin != null && end != null && begin.isBefore(end), Emp::getEntryDate, begin, end)
//                .orderByDesc(Emp::getUpdateTime);
//        this.page(empPage, queryWrapper);
//        this.lambdaQuery()
//                .like(StringUtils.isNotBlank(name), Emp::getName, name)
//                .eq(gender != null, Emp::getGender, gender)
//                .between(begin != null && end != null && begin.isBefore(end), Emp::getEntryDate, begin, end)
//                .orderByDesc(Emp::getUpdateTime)
//                .page(empPage);
//        List<Emp> records = empPage.getRecords();
//        records.forEach(emp -> {
//            Dept dept = deptMapper.selectById(emp.getDeptId());
//            Assert.notNull(dept, "员工必须属于一个部门");
//            emp.setDeptName(dept.getName());
//        });
        this.baseMapper.pageEmp(empPage, param);
        PageResult<Emp> pageResult = new PageResult<>(empPage.getTotal(), empPage.getRecords());
        return pageResult;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveEmpAndExpr(Emp emp) {
        emp.setPassword("123456");
//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (CollectionUtils.isNotEmpty(exprList)) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());
            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public void removeBatchByIdsAndExpr(List<Integer> ids) {
        List<EmpExpr> exprList = empExprService.list(new QueryWrapper<EmpExpr>().in("emp_id", ids));
        empExprService.removeByIds(exprList);
        this.removeByIds(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateByIdAndExpr(Emp emp) {
        LocalDateTime updateTime = LocalDateTime.now();
//        emp.setUpdateTime(updateTime);
        this.updateById(emp);
        empExprService.removeByIds(empExprService.list(new QueryWrapper<EmpExpr>().eq("emp_id", emp.getId())));
        List<EmpExpr> exprList = emp.getExprList();

        if (CollectionUtils.isNotEmpty(exprList)) {
            exprList.forEach(expr -> {
                expr.setEmpId(emp.getId());

            });
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public Emp getByIdAndExpr(Integer id) {
        Emp emp = this.getById(id);
        List<EmpExpr> exprList = empExprService.list(new QueryWrapper<EmpExpr>().eq("emp_id", id));
        emp.setExprList(exprList);
        return emp;
    }

    @Override
    public LoginResult login(Emp emp) {
        Emp emp1 = this.baseMapper.selectEmpByUserNameAndPassword(emp);
        if (emp1 != null) {
            //生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", emp1.getId());
            claims.put("username", emp1.getUsername());
            claims.put("name", emp1.getName());
            String jwt = JwtUtils.generateJwt(claims);
            return new LoginResult(emp1.getId(), emp1.getUsername(), emp1.getName(), jwt);
        }
        return null;

    }
}

